package pl.register.android.database.crud;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import pl.register.android.classes.ClassesTopic;
import pl.register.android.database.tables.ClassesTopicDBTable;
import pl.register.android.lesson.LessonProgram;

import java.security.KeyStore;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Mateusz Strzelecki
 * @since 2013-04-26
 */
public class ClassesTopicCRUD {

    private SQLiteDatabase database;

    public ClassesTopicCRUD(SQLiteDatabase database) {
        this.database = database;
    }

    public List<ClassesTopic> findClassesBy(LessonProgram lessonProgram) {
        List<ClassesTopic> classes = new ArrayList<ClassesTopic>();
        String where = ClassesTopicDBTable.FK_LESSON_PROGRAM_ID + " = " + lessonProgram.getId();
        Cursor cursor = database.query(ClassesTopicDBTable.TABLE_NAME, null, where, null, null, null, null);
        while (cursor.moveToNext()) {
            Long classesId = cursor.getLong(cursor.getColumnIndex(ClassesTopicDBTable.ID));
            String classesTopic = cursor.getString(cursor.getColumnIndex(ClassesTopicDBTable.TOPIC));
            int classesIsDoneInt = cursor.getInt(cursor.getColumnIndex(ClassesTopicDBTable.IS_DONE));
            classes.add(new ClassesTopic(classesId, classesTopic, classesIsDoneInt == 1));
        }
        cursor.close();
        return classes;
    }


    public ClassesTopic insertClassesFor(ClassesTopic classes, LessonProgram lessonProgram) {
        ContentValues insertValues = new ContentValues();
        insertValues.put(ClassesTopicDBTable.TOPIC, classes.getTopic());
        insertValues.put(ClassesTopicDBTable.IS_DONE, classes.isDone());
        insertValues.put(ClassesTopicDBTable.FK_LESSON_PROGRAM_ID, lessonProgram.getId());
        long rowId = database.insert(ClassesTopicDBTable.TABLE_NAME, null, insertValues);
        classes.setId(rowId);
        return classes;
    }

    public ClassesTopic updateClassesTopic(ClassesTopic classes) {
        String where = ClassesTopicDBTable.ID + " = " + classes.getId();
        ContentValues updateValues = new ContentValues();
        updateValues.put(ClassesTopicDBTable.TOPIC, classes.getTopic());
        updateValues.put(ClassesTopicDBTable.IS_DONE, classes.isDone());
        database.update(ClassesTopicDBTable.TABLE_NAME, updateValues, where, null);
        return classes;
    }

}